package com.nowcoder.community.d_controller;

import com.nowcoder.community.a_entity.*;
import com.nowcoder.community.c1_kafka.EventProducer;
import com.nowcoder.community.c_service.CommentService;
import com.nowcoder.community.c_service.DiscussPostService;
import com.nowcoder.community.c_service.LikeService;
import com.nowcoder.community.c_service.UserService;
import com.nowcoder.community.z_util.CommunityConstant;
import com.nowcoder.community.z_util.CommunityUtil;
import com.nowcoder.community.z_util.HostHolder;
import com.nowcoder.community.z_util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

@Controller
@RequestMapping("/discuss")//这个url不能写controller里
public class DiscussPostController implements CommunityConstant {
    @Autowired
    private DiscussPostService discussPostService;
    @Autowired
    private UserService userService;
    @Autowired
    private CommentService commentService;
    @Autowired
    private HostHolder hostHolder;
    @Autowired
    private LikeService likeService;

    @Autowired
    private EventProducer eventProducer;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * <p>——————————————————————————————————————————————-————
     * <p>   【当前类】DiscussPostController
     * <p>
     * <p>   【谁调用我】ajax独立开一条线程传数据（自异步定义）
     * <p>
     * <p>   【调用我干什么】+sql入ajax传过来的内容，并返回状态吗+msg给ajax显示
     * <p>——————————————————————————————————————————————-————
     */
    @ResponseBody//body不用model，因为不返回网页
    @RequestMapping(path = "/add",method = RequestMethod.POST)//ajax必post？
    public String addPost(String title,String content){
//        System.out.println(title+","+content);//拿到了

        //因为host在index不登录看不到发布按钮，所以此时必有userhost
        User user = hostHolder.getUser();

        DiscussPost post = new DiscussPost();
        post.setUserId(user.getId());//注意userid是user表的id！
        post.setTitle(title); post.setContent(content); post.setCreateTime(new Date());
        //插数据库-核心忘了，，里面处理敏感词
        discussPostService.addDiscussPost(post);

        //插sql库后，再放入kafa队列，之后写topic让消费者@被动+es库
        Event event = new Event()
                .setTopic(TOPIC_PUBLISH)
                .setUserId(user.getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(post.getId());//用e_t,e_id消费者调用相关普通Servcie
        eventProducer.fireEvent(event);


        //返回状态码+msg的json，方便网页处理？why-
        String res = CommunityUtil.javaToJsonString(0,"发布帖子成功~~（json）");
        return res;

    }


    /**
     * <p>——————————————————————————————————————————————-————
     * <p>   【当前类】DiscussPostController
     * <p>
     * <p>   【谁调用我】首页点击指定页面
     * <p>
     * <p>   【调用我干什么】查出特定页面信息->转发给detail.html新页面
     * <p>——————————————————————————————————————————————-————
     */
    @RequestMapping(path = "/detail/{discussPostId}", method = RequestMethod.GET)
    public String getOneDetailPost(Model model,
                                   Page page,//自动以"page",page塞入modeladd
                                   @PathVariable("discussPostId") int discussPostId){
        System.out.println(discussPostId);
        //先查帖子
        DiscussPost post = discussPostService.findPostById(discussPostId);
        model.addAttribute("post",post);
        //再用帖子行的userid查用户信息表
        User user = userService.findUserByid(post.getUserId());
        model.addAttribute("user",user);

        //——————————————继续写业务2，1级二级回复——————————————————————————
        page.setLimit(5);
        page.setRows(post.getCommentCount());//【区分】总上级当前讨论帖post，和回复帖comment

        //分页按钮重定向的前面帖postid，还需要html中加后面的
        // th:href="@{${page.path}(offset=${i-1}*${page.limit}, limit=${page.limit}
        page.setPath("/discuss/detail/"+discussPostId);//分页计算在html（因为要定位页号代码），java代码只负责sql简单查询


        //第一页也要按分页查！按page默认的值即可
        //先总model的list{看草纸图}
        List<Map<String,Object>> comList = new ArrayList<>();

        for(Comment c1:commentService.findComentRowByetype_eid__off_limt(1,
                                                                            post.getId(),
                                                                            page.getOffset(),
                                                                            page.getLimit()))
        {
            //c1——pojo智能取，只所以map，是因为还要拆user。。
            Map<String,Object> oneCom = new HashMap<>();

            oneCom.put("comment",c1);
            oneCom.put("user",userService.findUserByid(c1.getUserId()));
            //{不光2级回复加，一级也要加}+显示点赞数量和点赞状态（已赞）
            oneCom.put("likeCount",likeService.findEntityLikeCount(1,c1.getId()));
            int likeStatus = likeService.findEntityLikeStatus(hostHolder.getUser().getId(), 1,c1.getId());
            //返回的1、0状态码 之前redis写好的
            oneCom.put("likeStatus",likeStatus);


            //开始做放入二级回复reply oneCom.put("reply",reply)
            List<Map<String,Object>> reList_ofoneCom = new ArrayList<>();
            for(Comment reply:commentService.findComentRowByetype_eid__off_limt(2,
                                                                                c1.getId(),//核心【利用笨sql表，实现用1级id找2级id】

                                                                                0,//2级回复不做分页
                                                                                Integer.MAX_VALUE))
            {
                //pojo+user 必须Map<String,Object>
                Map<String,Object> oneReply = new HashMap<>();
                oneReply.put("reply",reply);
                oneReply.put("user",userService.findUserByid(reply.getUserId()));
                //回复目标 xx->bb:
                User tarUser = reply.getTargetId()==0?null:userService.findUserByid(reply.getTargetId());
                oneReply.put("target",tarUser);


                //+显示点赞数量和点赞状态（已赞）
                oneReply.put("likeCount",likeService.findEntityLikeCount(2,reply.getId()));
                likeStatus = likeService.findEntityLikeStatus(hostHolder.getUser().getId(), 2,reply.getId());
                //返回的1、0状态码 之前redis写好的
                oneReply.put("likeStatus",likeStatus);

                reList_ofoneCom.add(oneReply);
            }
            oneCom.put("reList",reList_ofoneCom);//可别忘放入comList


            comList.add(oneCom);


        }

        model.addAttribute("comList",comList);




        return "moban/site/discuss-detail";
    }

    /**
     * <p>————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
     * <p>      $ 置顶加精删除
     * <p>————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
     */
    // 置顶
    @RequestMapping(path = "/top", method = RequestMethod.POST)
    @ResponseBody
    public String setTop(int id) {
        discussPostService.updateType(id, 1);

        // 触发发帖事件
        Event event = new Event()
                .setTopic(TOPIC_PUBLISH)
                .setUserId(hostHolder.getUser().getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(id);
        eventProducer.fireEvent(event);

        return CommunityUtil.javaToJsonString(0);
    }

    // 加精
    @RequestMapping(path = "/wonderful", method = RequestMethod.POST)
    @ResponseBody
    public String setWonderful(int id) {
        discussPostService.updateStatus(id, 1);

        // 触发发帖事件
        Event event = new Event()
                .setTopic(TOPIC_PUBLISH)
                .setUserId(hostHolder.getUser().getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(id);
        eventProducer.fireEvent(event);
        /**
         * <p>————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
         * <p>      热帖定时存id【还有评论、新增、点赞Con要加】。计算评分在config-Qzjob中
         * <p>————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
         */

        // 存入redis id
        String redisKey = RedisKeyUtil.getPostScoreKey();
        redisTemplate.opsForSet().add(redisKey, id);

        return CommunityUtil.javaToJsonString(0);
    }

    // 删除
    @RequestMapping(path = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public String setDelete(int id) {
        discussPostService.updateStatus(id, 2);

        // 触发删帖事件
        Event event = new Event()
                .setTopic(TOPIC_DELETE)
                .setUserId(hostHolder.getUser().getId())
                .setEntityType(ENTITY_TYPE_POST)
                .setEntityId(id);
        eventProducer.fireEvent(event);

        return CommunityUtil.javaToJsonString(0);
    }

}
